package com.xz.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xz.usercenter.common.ErrorCode;
import com.xz.usercenter.exception.BusinessException;
import com.xz.usercenter.model.domain.User;
import com.xz.usercenter.service.UserService;
import com.xz.usercenter.mapper.UserMapper;
import com.xz.usercenter.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.xz.usercenter.constant.UserConstant.USER_ADMIN_ROLE;
import static com.xz.usercenter.constant.UserConstant.USER_LOGIN_STATUS;

/**
 * @author xuzhou
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-04-21 15:24:31
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    /**
     * 盐值 混淆密码
     */
    private static final String SIGN = "xz";

    /**
     * 用户注册
     *
     * @param userAccount      用户账号
     * @param userPassword     用户密码
     * @param checkPassword    重复密码
     * @param verificationCode 校验码
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String verificationCode) {
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度应大于等于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度应大于等于8位");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码输入不一致");
        }
        if (verificationCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "校验码长度应小于5位");
        }
        // 用户账号不能包含特殊字符
        String regEx = "^[a-zA-Z0-9_]+$";
        // String regEx = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        // matcher.find()
        if (!matcher.matches()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号不能包含特殊字符");
        }
        // 用户账号不允许重复
        Long count = lambdaQuery().eq(User::getUserAccount, userAccount).count();
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号重复");
        }

        // 校验码不允许重复
        count = lambdaQuery().eq(User::getVerificationCode, verificationCode).count();
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "校验码重复");
        }

        // 插入用户
        // 1.用户密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SIGN + userPassword).getBytes());
        // 2.保存数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setVerificationCode(verificationCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账号
     * @param userPassword 用户密码
     * @param request
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度应大于等于4位");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度应大于等于8位");
        }
        // 用户账号不能包含特殊字符
        String regEx = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (!matcher.matches()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号不能包含特殊字符");
        }
        // 用户密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SIGN + userPassword).getBytes());
        // 2.查询用户是否存在
        User user = lambdaQuery().eq(User::getUserAccount, userAccount).eq(User::getUserPassword, encryptPassword).one();
        if (user == null) {
//            log.info("用户账号或密码错误");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号或密码错误");
        }
        // 3.脱敏 防止把数据库的数据泄露给前端
        User safetyUser = getSafetyUser(user);
        // 4.记录用户的登录状态
        request.getSession().setAttribute(USER_LOGIN_STATUS, safetyUser);
        return safetyUser;
    }

    /**
     * 根据标签搜索用户。
     *
     * @param tagNameList 用户要搜索的标签列表
     * @param pageNum     当前页码
     * @param pageSize    每页大小
     * @return 分页后的用户列表
     */
    @Override
    public IPage<User> searchUsersByTags(List<String> tagNameList, long pageNum, long pageSize) {
        if (tagNameList != null && CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建分页参数
        Page<User> page = new Page<>(pageNum, pageSize);

        // sql 分页查询 调用新的分页查询方法
        IPage<User> userPage = sqlSearchWithPagination(tagNameList, page);

        return userPage;
    }

    /**
     * SQL分页查询，根据标签列表
     *
     * @param tagNameList 标签列表
     * @param page        分页对象
     * @return 分页后的用户列表
     */
    private IPage<User> sqlSearchWithPagination(List<String> tagNameList, Page<User> page) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        //数据库中tags 的值 ["Java","C++","Python"]
        //拼接tag
        // like '%Java%' and like '%Python%'
        for (String tagList : tagNameList) {
            // 这样可以将多个LIKE条件用OR连接起来，找到包含任一标签的用户
            queryWrapper = queryWrapper.or().like("tags", tagList);
        }

        // 执行分页查询
        return this.page(page, queryWrapper);
    }

    /**
     * sql运行查询
     *
     * @param tagNameList
     * @return
     */
    private List<User> sqlSearch(List<String> tagNameList) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        long starTime = System.currentTimeMillis();
        //拼接tag
        // like '%Java%' and like '%Python%'
        for (String tagList : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagList);
        }
        List<User> userList = this.list(queryWrapper);
        log.info("sql 运行 时间 = " + (System.currentTimeMillis() - starTime));
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 查询，内存运行筛选
     *
     * @param tagNameList 标签名列表
     * @return
     */
    private List<User> memorySearch(List<String> tagNameList) {
        //1.先查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // long starTime = System.currentTimeMillis();
        List<User> userList = this.list(queryWrapper);
        Gson gson = new Gson();
        //2.判断内存中是否包含要求的标签 parallelStream()
        return userList.stream().filter(user -> {
            String tagStr = user.getTags();
            if (StringUtils.isBlank(tagStr)) {
                return false;
            }
            Set<String> tempTagNameSet = gson.fromJson(tagStr, new TypeToken<Set<String>>() {
            }.getType());
            //java8  Optional 来判断空  如果为空 给个默认值
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());

            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
        // log.info("memory query time = " + (System.currentTimeMillis() - starTime));
    }

    /**
     * 用户信息修改
     *
     * @param user
     * @return
     */
    @Override
    public Boolean updateUser(User user, User loginUser) {
        long userId = user.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 校验，如果用户没有传任何要更新的值，就直接报错，不用执行 update 语句
        // 创建一个与user对象相同但移除所有空字段的新对象
        User userWithoutNulls = new User();
        EqualsBuilder builder = new EqualsBuilder();
        for (Field field : User.class.getDeclaredFields()) {
            try {
                field.setAccessible(true);
                // 获取旧对象的字段值
                Object oldFieldValue = field.get(loginUser);
                // 获取新对象的字段值
                Object newValue = field.get(user);
                if (newValue != null) {
                    field.set(userWithoutNulls, newValue);
                    builder.append(oldFieldValue, newValue);
                }
            } catch (IllegalAccessException e) {
                log.error("访问用户字段失败  ", e);
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "访问用户字段失败");
            }
        }

        // 比较新旧对象，如果相等，表示没有要更新的值
        if (builder.isEquals()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有要更新的值");
        }

        //如果是管理员，允许更新任意用户
        //如果不是管理员，只允许更新自己的信息
        if (!isAdmin(loginUser) && userId != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User userOld = this.getById(userId);
        if (userOld == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return this.updateById(user);
    }

    /**
     * 获取当前用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATUS);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return (User) userObj;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User user = (User) userObj;
        return user != null && Objects.equals(user.getUserRole(), USER_ADMIN_ROLE);
    }

    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && Objects.equals(loginUser.getUserRole(), USER_ADMIN_ROLE);
    }

    /**
     * 编辑距离算法推荐用户
     *
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        // 当前用户的 tags
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (User user : userList) {
            String userTags = user.getTags();
            // 无标签或者为当前用户自己，跳过
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), loginUser.getId())) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list
                .stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本的顺序的 userId 列表
        List<Long> userIdList = topUserPairList
                .stream()
                .map(pair -> pair.getKey().getId())
                .collect(Collectors.toList());

        return getFinalUsersByMemory(userIdList);
    }

    /**
     * 根据id顺序集合获取用户组（sql版）
     *
     * @param userIdList 带顺序的id集合
     * @return 用户组
     */
    private List<User> getFinalUsersBySql(List<Long> userIdList) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        userQueryWrapper.last("order by field(id," + StringUtils.join(userIdList, ",") + ")");
        return this.list(userQueryWrapper).stream().map(this::getSafetyUser).collect(Collectors.toList());
    }


    /**
     * 根据id顺序集合获取用户组（内存版）
     *
     * @param userIdList 带顺序的id集合
     * @return 用户组
     */
    private List<User> getFinalUsersByMemory(List<Long> userIdList) {
        //根据id查询user完整信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper).stream()
                .map(this::getSafetyUser)
                .collect(Collectors.groupingBy(User::getId));
        // 因为上面查询打乱了顺序，这里根据上面有序的userID列表赋值
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除用户登录态
        request.getSession().removeAttribute(USER_LOGIN_STATUS);
        return 1;
    }

    /**
     * 用户脱敏 防止把数据库的数据泄露给前端
     *
     * @param originalUser 原始数据
     * @return
     */
    @Override
    public User getSafetyUser(User originalUser) {
        if (originalUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyUser = new User();
        safetyUser.setId(originalUser.getId());
        safetyUser.setUserName(originalUser.getUserName());
        safetyUser.setUserAccount(originalUser.getUserAccount());
        safetyUser.setAvatarUrl(originalUser.getAvatarUrl());
        safetyUser.setUserRole(originalUser.getUserRole());
        safetyUser.setGender(originalUser.getGender());
        safetyUser.setPhone(originalUser.getPhone());
        safetyUser.setEmail(originalUser.getEmail());
        safetyUser.setTags(originalUser.getTags());
        safetyUser.setProfile(originalUser.getProfile());
        safetyUser.setVerificationCode(originalUser.getVerificationCode());
        safetyUser.setUserStatus(originalUser.getUserStatus());
        safetyUser.setCreateTime(originalUser.getCreateTime());
        return safetyUser;
    }
}




